<template>
  <view class="guess_box">
    <!-- 标题 -->
    <view class="guess_text">
      <image style="width: 25rpx; height: 25rpx" src="@/static/images/yuan.png" />
      <text class="text">猜你喜欢</text>
      <image style="width: 25rpx; height: 25rpx" src="@/static/images/yuan.png" />
    </view>
    <!-- 商品 -->
    <view class="goods_box">
      <!-- 每个商品 -->
      <view class="goods_item" v-for="item in guessList" :key="item.id">
        <navigator :url="`/pages/goodsDetail/goodsDetail?id=${item.id}`" style="width: 100%; height: 100%;">
          <image :src="item.picture" class="image" />
          <view>{{ item.name }}</view>
          <view class="price_box">￥{{ item.price }}</view>
        </navigator>
      </view>
    </view>
    <view class="bottom">{{ tipText }}</view>
  </view>
</template>

<script lang="ts" setup>
import { getGuessAPI } from '@/api/home'
import type { goodsType } from '@/types/global'
import { onMounted, ref } from 'vue'
// 猜你喜欢商品列表
const guessList = ref<goodsType[]>([] as goodsType[])
// 当前页
const page = ref(1)
// 每页大小
const pageSize = ref(10)
// 总页数
const pages = ref(0)
// 底部文字
const tipText = ref<string>('正在加载...')
// 获取猜你喜欢商品数据的函数
const getGuessData = async () => {
  const res = await getGuessAPI(page.value, pageSize.value)
  if (res.code === '1') {
    guessList.value!.push(...res.result.items)
    pages.value = res.result.pages
  }
}
// 滚动到底部的回调
const scrolltolower = () => {
  // 判断当前页是否小于最后一页
  if (page.value < pages.value) {
    page.value = page.value + 1
    // 重新调用获取
    getGuessData()
    tipText.value = '正在加载...'
  } else {
    tipText.value = '到底啦~'
  }
}
// 重置猜你喜欢数据的方法
const resetData = () => {
  page.value = 1
  pageSize.value = 10
  guessList.value = []
}
onMounted(() => {
  getGuessData()
})
// 暴露方法
defineExpose({
  scrolltolower,
  getGuessData,
  resetData,
})
</script>

<style lang="scss">
@import './style/tphGuess.scss';
</style>
